package org.zoomdev.zoom.http;

import okhttp3.Headers;
import org.zoomdev.zoom.common.io.Io;
import org.zoomdev.zoom.common.json.JSON;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class Response {

    private final okhttp3.Response resp;
    private final Request request;


    Response(Request request, okhttp3.Response resp) {
        this.request = request;
        this.resp = resp;
    }


    public String string() throws IOException {
        try {
            return resp.body().string();
        } finally {
            close();
        }
    }

    public InputStream stream() {
        return resp.body().byteStream();
    }

    public <T> T json(Class<T> classOfT) {
        try {
            return JSON.parse(resp.body().byteStream(), classOfT);
        } finally {
            close();
        }
    }


    public byte[] bytes() throws IOException {
        try {
            return resp.body().bytes();
        } finally {
            close();
        }

    }

    public void close() {
        Io.close(resp);
    }

    public int statusCode() throws IOException {
        return resp.code();
    }


    public String header(String key) {
        return resp.header(key);
    }

    public Map<String, String> headers() {
        Headers headers = resp.headers();
        Map<String, String> ret = new HashMap<String, String>();
        for (String name : headers.names()) {
            List<String> list = headers.values(name);
            if (!list.isEmpty()) {
                ret.put(name, list.get(0));
            }
        }
        return ret;
    }

    public Request getRequest() {
        return request;
    }
}
